﻿// <copyright file="HandlePanorama.cs" company="Microsoft Corporation">
// Copyright (c) 2010 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-09-10</date>
// <summary>Silverlight Analytics Framework Panorama control handler for Windows Phone 7</summary>

namespace Microsoft.WebAnalytics.Controls
{
    using System;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Windows.Controls;
    using Microsoft.Phone.Controls;
    using Microsoft.WebAnalytics;
    using Microsoft.WebAnalytics.Contracts;

    /// <summary>
    /// Track a Windows Phone 7 Panorama SelectionChanged event
    /// </summary>
    /// <remarks>
    /// <list type="table">
    /// <item>
    /// <term>Platforms</term>
    /// <description>Windows Phone 7</description>
    /// </item>
    /// <item>
    /// <term>AnalyticsEvent.Name</term>
    /// <description>SelectionChanged</description>
    /// </item>
    /// <item>
    /// <term>AnalyticsEvent.ActionValue</term>
    /// <description>Panorama Name or Panorama.Header</description>
    /// </item>
    /// </list>
    /// </remarks>
    [Tracker(typeof(Panorama))]
    public class HandlePanorama : ITrackHandler
    {
        #region Properties
        /// <summary>
        /// Gets or sets the event Logging method
        /// </summary>
        [Import("Log")]
        public Action<AnalyticsEvent> Log { get; set; }
        #endregion

        #region ITrackAction Members

        /// <summary>
        /// Track the Panorama.SelectionChanged event
        /// </summary>
        /// <param name="associatedObject">the associated object</param>
        /// <param name="analyticsEvent">the analytics event</param>
        /// <param name="eventArgs">the event arguments</param>
        public void Track(
            System.Windows.FrameworkElement associatedObject,
            AnalyticsEvent analyticsEvent,
            System.EventArgs eventArgs)
        {
            if (analyticsEvent.Name == "SelectionChanged")
            {
                var args = eventArgs as SelectionChangedEventArgs;

                var newItems = from item in args.AddedItems.Cast<PanoramaItem>()
                               select string.IsNullOrEmpty(item.Name) ? item.Header.ToString() : item.Name;

                var items = string.Join("|", newItems.ToArray());

                analyticsEvent.ActionValue = items;
            }

            this.Log(analyticsEvent);
        }

        #endregion
    }
}
